(function($, undefined) {
	var ntd = {};
	/** Read the new task and add it to the list */
	ntd.add = function(event) {
		// Read the task from the input
		var task=$('input').val();
		if (task) {
			// Add the task to array and refresh list
			ntd.list[ntd.list.length] = task;
			ntd.refresh_list();
			// Clear the input
			$('input').val('');
		}
		event.preventDefault();
	};
	/** Remove the task which was marked as selected */
	ntd.remove = function() {
		// Remove from array and refresh list
		ntd.list.splice(ntd.selected,1);
		ntd.refresh_list();
	};
	/** Recreate the entire list from the available list of tasks */
	ntd.refresh_list = function() {
		var $tasks = $('#task_list'), i;
		// Clear the existing task list
		$tasks.empty();
		if (ntd.list.length) {
			// Add the header
			$tasks.append('<li data-role="list-divider">Not To Do&#39;s</li>');
			for (var i=0;i<ntd.list.length;i++){
				// Append each task
				var li = '<li><a data-rel="dialog" data-task="' + i
						+ '" href="#confirm">' + ntd.list[i] + '</a></li>'
				$tasks.append(li);
			}
		}
		// Store back the list
		localStorage.list = JSON.stringify(ntd.list || []);
		// Add the header for addition of new tasks
		$tasks.append('<li data-role="list-divider">Add a task</li>');
		// Use jQuery Mobile's listview method to refresh
		$tasks.listview('refresh');
	};
	$(function(){
		// If no list is already present, initialize it
		if (!localStorage.list) {
			localStorage.list = "[]";
		}
		// Load the list by parsing the JSON from localStorage
		ntd.list = JSON.parse(localStorage.list || "[]");
		$('#add').click(ntd.add);
		// Refresh the list everytime the page is reloaded
		$('#index').live('pagecreate',ntd.refresh_list);
		$('li a').live('click',function() {
			ntd.selected = $(this).data('task');
		});
		$('.remove_task').click(ntd.remove);
	});
})(jQuery);
